package org.zqh.ncc.thread;

import com.alibaba.fastjson.JSON;
import nccloud.open.api.auto.token.cur.utils.APICurUtils;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.stereotype.Component;
import org.zqh.ncc.config.NcConfig;
import org.zqh.ncc.config.YmToErp;
import org.zqh.ncc.ncmodel.DH.BillInfo;
import org.zqh.ncc.ncmodel.DH.JsonRootBean;
import org.zqh.ncc.ncmodel.DH.Po_order;
import org.zqh.ncc.ncmodel.DH.Po_order_b;
import org.zqh.ncc.ncmodel.NcBillReturn;
import org.zqh.ncc.utils.TimeUtil;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.PriorityBlockingQueue;

/**
 * 定时扫描t_bangdan_jl表，发现有需要推NC单据的记录，就进行处理,该线程只处理京粮玉米
 */
@Component
public class JlymToErpThread extends CommonThread<YmToErp> {
    volatile long beginTime = 0;
    NcConfig ncConfig;
    PriorityBlockingQueue<YmToErp> jlymToErpQueue;
    APICurUtils apiCurUtils;

    public JlymToErpThread(PriorityBlockingQueue<YmToErp> jlymToErpQueue, @Qualifier("jlymApiCurUtils") APICurUtils apiCurUtils, NcConfig ncConfig) {
        super(jlymToErpQueue);
        this.apiCurUtils = apiCurUtils;
        this.ncConfig = ncConfig;
        apiCurUtils.init(ncConfig.getJl_ym_ip(), ncConfig.getJl_ym_port(), ncConfig.getJl_biz_center(), ncConfig.getJl_client_id(), ncConfig.getJl_client_secret(), ncConfig.getJl_pubKey(), ncConfig.getJl_user_name(), ncConfig.getJl_pwd());
        this.setName("jlymToErpThread");
    }

    /**
     * 线程启动运行，推送
     */
    public void run() {
        while (!isStopping) {
            try {
                List<YmToErp> bdList = getJlymToErpList(10);
                if (bdList.size() > 0) {
                    processList(bdList);
                    beginSleep(100);
                } else {
                    beginSleep(3000);
                }
            } catch (Exception e) {
                log.error("", e);
                beginSleep(10000);
            }
        }
        isStopped = true;
    }

    /**
     * @param bdList
     */
    private void processList(List<YmToErp> bdList) {
        beginTime = System.currentTimeMillis();
        for (YmToErp ymToErp : bdList) {
            log.debug("before jlymToErp post :" + ymToErp);
            try {
//                token = apiCurUtils.getToken();
                apiCurUtils.setApiUrl(ncConfig.getJl_url());
                String sendJson = toErpPoOrder(ymToErp);
                log.info("send: " + ncConfig.getJl_ym_ip() + ":" + ncConfig.getJl_ym_port() + " json=" + sendJson);
                String apiRetrun = apiCurUtils.getAPIRetrun(apiCurUtils.getToken(), sendJson);
                log.info((System.currentTimeMillis() - beginTime) + " ms return: " + apiRetrun);
                NcBillReturn ncBillReturn = JSON.parseObject(apiRetrun, NcBillReturn.class);
                if (null != ncBillReturn) {
                    if (null == ncBillReturn.getMessage())
                        ncBillReturn.setMessage("null");
                    else if (ncBillReturn.getMessage().length() > 300) {
                        ncBillReturn.setMessage(ncBillReturn.getMessage().replaceAll("'", "#"));
                        ncBillReturn.setMessage(ncBillReturn.getMessage().substring(ncBillReturn.getMessage().length() - 298));
                    }
                    String sql = "update t_bangdan_jl set resulttime=sysdate,resultmemo='" + ncBillReturn.getMessage() + "',resulttoerp='" + (ncBillReturn.isSuccess() ? "1" : "-1") +
                            "' where vbdcode='" + ymToErp.getVbdcode() + "'";
                    try {
                        jdbcTemplate.update(sql);
                    } catch (Exception sqlError) {
                        log.error("sql=" + sql, sqlError);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                log.error("调用接口错误：", e);
            }
        }
    }

    /**
     * 先更新t_bangdan_jl表，加上一个uuid,后面根据这个uuid进行select，更新那些需要同步推送到京粮NC的过磅单，根据resulttoerp字段的值
     *
     * @param count 每次处理的数量
     * @return
     */
    private List<YmToErp> getJlymToErpList(int count) {
        List<YmToErp> bdList = new ArrayList<>();
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        int rowCount = 0;
        String sql = "update t_bangdan_jl set resulttoerp='2',updateuuid='" + uuid + "',duuidtime=sysdate  where vbdtype='DH' and resulttoerp='0' and vdelflag='0' and rownum <= " + count;
        try {
//            log.info("jlym sql = " + sql);
            rowCount = jdbcTemplate.update(sql);
        } catch (Exception sqlError) {
            log.error("sql=" + sql, sqlError);
        }
        if (rowCount > 0) {
            bdList = jdbcTemplate.query("select * from v_bd_jingliang where updateuuid='" + uuid + "'", new BeanPropertyRowMapper(YmToErp.class));
            if (bdList.size() != rowCount) {
                log.warn("uuid=" + uuid + " updateCount=" + rowCount + " getCount=" + bdList.size() + ", 注意检查");
            }
        }
        return bdList;
    }

    /**
     * 从视图返回的对象，转换为json，传递给NC接口，推式生成采购订单
     *
     * @param ymToErp
     * @return
     */
    private String toErpPoOrder(YmToErp ymToErp) {
        JsonRootBean jb = new JsonRootBean();
        BillInfo billInfo = new BillInfo();
        Po_order po_order = new Po_order();
        Po_order_b po_order_b = new Po_order_b();
        po_order.setBillmaker(ymToErp.getBillmaker());
        po_order.setPk_dept(ymToErp.getPkdept());
        po_order.setPk_org(ymToErp.getPkorg());
        po_order.setPk_org_v(ymToErp.getPkorg());
        po_order.setVtrantypecode(ymToErp.getVtrantypecode());
        po_order.setDbilldate(TimeUtil.getStrDateFormat(new Date()));
        po_order.setPk_supplier(ymToErp.getVfromcode());
        po_order.setPk_invcsupllier(ymToErp.getVfromcode());
        po_order.setVdef21(ymToErp.getInspector());
        po_order.setVdef22(ymToErp.getVuncart());
        //冲销的单据，算作退货，需要设置breturn=Y
        if (ymToErp.getVbdcode().indexOf("-") > 0)
            po_order.setBreturn("Y");
        else
            po_order.setBreturn("N");

        po_order_b.setCorigcurrencyid(ymToErp.getOrigcurrencyid());
        po_order_b.setCtaxcodeid(ymToErp.getTaxcodeid());
        po_order_b.setPk_material(ymToErp.getVmatcode());
        po_order_b.setNqtorigtaxprice(ymToErp.getNprice());
        po_order_b.setVbdef14("" + ymToErp.getNpizhong());
        po_order_b.setVbdef15(TimeUtil.getStrDateFormat(ymToErp.getDouttime()));
        po_order_b.setVbdef16("" + ymToErp.getNmaozhong());
        po_order_b.setVbdef17(TimeUtil.getStrDateFormat(ymToErp.getDintime()));
        po_order_b.setVbdef18("" + ymToErp.getNjingzhong());
        po_order_b.setVbdef19(ymToErp.getVcarno());
        po_order_b.setVbdef20(ymToErp.getVbdcode());

        po_order_b.setPk_recvstordoc(ymToErp.getVstorname());

        int ibwc = Math.round(ymToErp.getNjingzhong() * ymToErp.getPkouwater() / 100);
        po_order_b.setVbdef29("" + ibwc);//扣水重

        int ibmz = Math.round(ymToErp.getNjingzhong() * ymToErp.getPkouza() / 100);
        po_order_b.setVbdef30("" + ibmz);//扣杂重
        //po_order_b.setVbdef30("" + ymToErp.getNzazhong());//扣杂重

        int ibm = Math.round(ymToErp.getNjingzhong() * ymToErp.getPkoumb() / 100);
        po_order_b.setVbdef31("" + ibm);//扣霉变

        int ibi = Math.round(ymToErp.getNjingzhong() * ymToErp.getPkoubjz() / 100);
        po_order_b.setVbdef32("" + ibi);//扣并肩杂

        int ibbd = Math.round(ymToErp.getNjingzhong() * ymToErp.getPkourz() / 100);
        po_order_b.setVbdef44("" + ibbd);//扣容重
        //主数量是结算净重，=过磅净重-扣水杂后的重量
        po_order_b.setNnum(ymToErp.getNjszhong());

        po_order_b.setVbdef33("" + ymToErp.getNkouzhong());//皮重附加,一般用于微调净重，正数为加，负数为减
        po_order_b.setVbdef34("" + (ymToErp.getNsxwzhong() + ymToErp.getNjiakou()));//筛下物+加扣重量
        po_order_b.setVbdef35("" + ymToErp.getPwater());//水份%
        po_order_b.setVbdef36("" + ymToErp.getPza());//杂质%
        po_order_b.setVbdef37("" + ymToErp.getPmb());//霉变%
        po_order_b.setVbdef38("" + ymToErp.getPbjz());//并肩杂%
        po_order_b.setVbdef39("" + ymToErp.getPkouwater());//扣水份%
        po_order_b.setVbdef40("" + ymToErp.getPkouza());//扣杂质%
        po_order_b.setVbdef41("" + ymToErp.getPkourz());//扣容重%
        po_order_b.setVbdef42("" + ymToErp.getPkoumb());//扣霉变%
        po_order_b.setVbdef43("" + ymToErp.getPkoubjz());//扣并肩杂%
        po_order_b.setVbdef45(ymToErp.getVqccode());//质验单编号
        po_order_b.setVbdef47(ymToErp.getVinjby());//监磅员
        po_order_b.setVbdef48(ymToErp.getVingby());//过磅员
        po_order_b.setVbdef49("" + ymToErp.getPrz());//容重
        billInfo.setPo_order(po_order);
        List<Po_order_b> blist = new ArrayList<>();
        blist.add(po_order_b);
        billInfo.setPo_order_b(blist);
        List<BillInfo> billInfoList = new ArrayList<>();
        billInfoList.add(billInfo);
        jb.setBillInfo(billInfoList);

        return JSON.toJSONString(jb);
    }

}
